import os

from aiogram import F
from aiogram.enums import ContentType
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.api.entities import MediaAttachment
from aiogram_dialog.widgets.kbd import (
    Back,
    Cancel,
    NextPage,
    NumberedPager,
    PrevPage,
    Row,
    StubScroll,
)
from aiogram_dialog.widgets.media import DynamicMedia
from aiogram_dialog.widgets.text import Const, Format

from poker_bot.core.constants import REVIEWS_FOLDER
from poker_bot.database.services import ReviewService
from poker_bot.tg_bot.states import ReviewsSG

from ...extras import copy_start_data_to_ctx
from ...widgets import LocaleText


async def review_getter(
    dialog_manager: DialogManager, review_service: ReviewService, **kwargs
):
    reviews = await review_service.get_reviews()
    current_page = await dialog_manager.find("reviews_scroll").get_page()

    if not reviews or current_page >= len(reviews):
        return {
            "pages": 0,
            "current_page": 0,
            "review_text": None,
            "review_date": None,
            "review_screenshot": None,
        }

    review = reviews[current_page]
    if current_page + 1 >= len(reviews):
        await dialog_manager.find("reviews_scroll").set_page(-1)

    try:
        file_path = os.path.join(REVIEWS_FOLDER, review.image_path)
        review_screenshot = (
            MediaAttachment(path=file_path, type=ContentType.PHOTO)
            if os.path.isfile(file_path)
            else None
        )
    except TypeError:
        review_screenshot = None

    return {
        "pages": len(reviews),
        "current_page": current_page + 1,
        "review_text": review.review_text,
        "review_date": review.review_date,
        "review_screenshot": review_screenshot,
    }


reviews_list_window = Window(
    Format("{review_text}\n", when=F["review_text"]),
    Const("Сейчас нет отзывов", when=~F["review_text"]),
    DynamicMedia(
        "review_screenshot",
        when=(F["review_screenshot"]),
    ),
    StubScroll(id="reviews_scroll", pages="pages"),
    NextPage(text=Const("Еще отзыв"), scroll="reviews_scroll"),
    Cancel(LocaleText("back-btn")),
    state=ReviewsSG.reviews_list,
    getter=review_getter,
    preview_data=review_getter,
    disable_web_page_preview=False,
)

reviews_dialog = Dialog(
    reviews_list_window,
    on_start=copy_start_data_to_ctx,
)
